package com.danceforyou.common.restful.exception;

import com.danceforyou.common.restful.ResponseT;
import com.danceforyou.common.restful.RtnCodeEnum;
import com.danceforyou.common.util.LoggerUtil;
import cz.jirutka.spring.exhandler.handlers.RestExceptionHandler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
public class BizExceptionHandler implements RestExceptionHandler {

    private static final LoggerUtil LOGGER_UTIL = LoggerUtil.getLogger("methodError");
    public ResponseEntity handleException(Exception exception, HttpServletRequest request) {
        boolean isDebug = false;
        if (request.getParameter("debug") != null) {
            isDebug = true;
        }

        ResponseT responseT;
        if (exception instanceof BizException) {
            responseT = new ResponseT((BizException) exception, isDebug);
            LOGGER_UTIL.error(((BizException) exception).getMsg());
        } else {
            BizException bizException;
            if (isDebug) {
                bizException = new BizException(RtnCodeEnum.OTHER.getCode(), RtnCodeEnum.OTHER.getMsg());
            } else {
                bizException = new BizException(RtnCodeEnum.OTHER.getCode(), RtnCodeEnum.OTHER.getMsg(), exception);
            }
            responseT = new ResponseT(bizException, isDebug);
            StringWriter writer = new StringWriter();
            exception.printStackTrace(new PrintWriter(writer, true));
            LOGGER_UTIL.error(writer.toString());
        }

        return new ResponseEntity(responseT, HttpStatus.OK);
    }
}
